import {Component, OnInit} from '@angular/core';
import {TabVo} from './vo/TabVo';
import {MenuVo} from './vo/MenuVo';
import {ActivationEnd, NavigationEnd, Router} from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

  isCollapsed = false;

  tabs :Array<TabVo>;
  path='';
  tabindex=0;
  menuarray:Array<MenuVo>;


  constructor(private router:Router){
    this.tabs=new Array();
    this.menuarray=new Array<MenuVo>();
  }

  ngOnInit(): void {

    this.firePathChange();
    this.initMenu();
    this.initfirstTab();
  }


  closeTab({ index }: { index: number }): void {
    this.tabs.splice(index, 1);

  }


  firePathChange(){
    let path = '';

    this.router.events.subscribe((event) => {
      //console.log(event);

      if(event instanceof ActivationEnd) {
        if(event.snapshot) {
          if(event.snapshot.routeConfig && event.snapshot.routeConfig.path) {
            path = path == '' ? event.snapshot.routeConfig.path : [event.snapshot.routeConfig.path, path].join('/');
          }
        }
      }

      if (event instanceof NavigationEnd) {
        //save the path, and clear it.

        this.path = path;
        path = '';
        console.log(this.path);
        this.dealTab();

      }



    });
  }


  dealTab(){
    let exsisttab=this.tabs.find((t)=>t.url==this.path);
    if(exsisttab){
      this.tabindex=exsisttab.index!;
    }
    else{
      this.addTab();
    }


  }


  addTab(){
    let tempmunu=this.menuarray.find((m)=>m.url==this.path);
    if(tempmunu){
      let t =new TabVo();
      t.title=tempmunu.title;
      t.url=tempmunu.url;
      t.index=this.tabindex+1;
      t.canclouse=true;
      this.tabs.push(t);
      this.tabindex=this.tabindex+1;
    }



  }


  initMenu(){

    let m1=new MenuVo();
    m1.url='welcome';
    m1.title='看板';
    this.menuarray.push(m1);

    let m2=new MenuVo();
    m2.url='attendance';
    m2.title='考勤管理';
    this.menuarray.push(m2);

    let m3=new MenuVo();
    m3.url='primeorg';
    m3.title='组织机构';
    this.menuarray.push(m3);

  }


  initfirstTab(){
    let v=new TabVo();
    v.title="看板";
    v.url='welcome';
    v.index=0;
    v.canclouse=false;
    this.tabs.push(v);
    this.tabindex=0;
  }


  clouseAllTab(){
    this.tabs.splice(1,this.tabs.length);
    this.router.navigate(['welcome'])
  }


  onTabChange(e:any){
    console.log("当前的tab  "+e)

    let currenttab= this.tabs.find((t)=>t.index==e)
    if(currenttab){
      console.log("当前选中的tab"+currenttab.title);
      this.router.navigate([currenttab.url]);
    }
  }








}
